package service

import (
	"encoding/json"
	"errors"
	"rongyy/src/constants"
	"rongyy/src/helper"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"time"
)

type OcrService struct {
}

// 公卫，7院卡管中心用， fetch去调用https:// + ip的接口，要报错，直接报dnsname非法，不晓得扎个解决。所以从这里转一哈，艹

func (ps *OcrService) IdOcr(sEnc string) (*models.OcrResult, error) {
	if !time.Now().Before(constant.OcrTokenExpireDate) {
		oauthBody, err := helper.PostOcrOauth()
		if err != nil {
			return nil, err
		}
		oauthResult := &models.OcrOauth{}
		err = json.Unmarshal(oauthBody, oauthResult)
		if err != nil {
			middlewares.Logger.Println("IdOcr oauth Unmarshal ", err, string(oauthBody))
			return nil, err
		}
		constant.OcrToken = oauthResult.AccessToken
		constant.OcrTokenExpireDate = time.Unix(time.Now().Unix()+oauthResult.ExpiresIn-259200, 0) // 过期时间一个月 -259200:提前三天
	}

	uri := "?access_token=" + constant.OcrToken
	body, err := helper.PostOcr(uri, "data:image/jpeg;base64,"+sEnc)
	if err != nil {
		return nil, err
	}

	result := &models.OcrResult{}
	err = json.Unmarshal(body, result)
	if err != nil {
		middlewares.Logger.Println("IdOcr Unmarshal ", err, string(body))
		return nil, err
	}
	middlewares.Logger.Println("result is not success ", result)
	if result.ImageStatus != "normal" {
		middlewares.Logger.Println("result is not success ", result.ImageStatus)
		return nil, errors.New("身份证识别出错")
	}
	return result, nil
}
